from http import HTTPStatus
import dashscope
import os
import openai
from mylogger import logger
from dotenv import load_dotenv
import time
from tenacity import (
    retry,
    stop_after_attempt,
    wait_random_exponential,
)  # for exponential backoff

load_dotenv()

dashscope.api_key=os.environ.get('DASHSCOPE_API_KEY')

def demo():
    prompt_text = '用萝卜、土豆、茄子做饭，给我个菜谱。'
    resp = dashscope.Generation.call(
        model='qwen-max',
        prompt=prompt_text,
        top_p=0.9
    )
    # The response status_code is HTTPStatus.OK indicate success,
    # otherwise indicate request is failed, you can get error code
    # and message from code and message.
    if resp.status_code == HTTPStatus.OK:
        logger.info(resp.output)  # The output text
        logger.info(resp.usage)  # The usage information
    else:
        logger.info(resp.code)  # The error code.
        logger.info(resp.message)  # The error message.



class DialogueInterface:
    def __init__(self):
        # 初始化接口
        pass

    def startChat(self, messageStr):
        # 启动对话，返回对话的初始信息
        # 返回对话内容
        pass

    def resetChat(self):
        # 重新开始对话，清除对话历史
        pass


class QWenChat(DialogueInterface):
    def __init__(self):
        self.messages = [{'role': 'system', 'content': 'You are a helpful assistant.'}]

    def startChat(self, messageStr):
        # 非正常回复我们尝试3次，否则就抛出异样了
        self.messages.append({"role": "user", "content": messageStr})
        
        for _ in range(3):
            response = dashscope.Generation.call(
                dashscope.Generation.Models.qwen_max,
                messages=self.messages,
                result_format='message',  # set the result to be "message" format.
            )
            assistentResponse = ""
            if response.status_code == HTTPStatus.OK:
                assistentResponse = response['output']['choices'][0]['message']['content']
                self.messages.append({"role": "assistant", "content": assistentResponse})
                return assistentResponse
            else:
                logger.info('Request id: %s, Status code: %s, error code: %s, error message: %s' % (
                    response.request_id, response.status_code,
                    response.code, response.message
                ))
        else:
            logger.info(self.messages)
            self.messages.pop()
            raise Exception("3 次请求故障, 无法获得回答")
                

    def resetChat(self):
        # 重新开始对话，清除对话历史
        self.messages = []
        

class SFChat(DialogueInterface):
    def __init__(self, model="01-ai/Yi-1.5-9B-Chat-16K"):
        self.client = openai.OpenAI(
            api_key=os.environ.get('SILICONFLOW_SECRET'), # 从https://cloud.siliconflow.cn/account/ak获取
            base_url="https://api.siliconflow.cn/v1"
        )
        self.messages = [{'role': 'system', 'content': 'You are a helpful assistant.'}]
        self.model = model

    def startChat(self, messageStr):
        self.messages.append({"role": "user", "content": messageStr})
        response = self._conversation(self.messages)
        # print(self.messages, response)
        assistentResponse = response.choices[0].message.content
        self.messages.append({"role": "assistant", "content": assistentResponse})
        return assistentResponse

    @retry(wait=wait_random_exponential(min=1, max=60), stop=stop_after_attempt(20))
    def _conversation(self, messages):
        return self.client.chat.completions.create(
                model=self.model,
                messages=messages,
            )
                

    def resetChat(self):
        # 重新开始对话，清除对话历史
        self.messages = []
        